//
//  AnswerDisplayView.m
//  record_plugin
//
//  Created by zqj on 2024/9/9.
//  回答和回答结果展示页面

#import "AnswerDisplayView.h"

@implementation AnswerDisplayView

+ (AnswerDisplayView *)instance{
    AnswerDisplayView *view = [[NSBundle bundleForClass:[self class]] loadNibNamed:@"AnswerDisplayView" owner:self options:nil].firstObject;
    return view;
}

- (void)updateIsAnswer:(BOOL)isAnswer content:(NSString *)content{
    NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"voice" ofType:@"gif"];
    self.answerImgV.image = [self decodeGifImageByData:[NSData dataWithContentsOfFile:path]];
  
    if (isAnswer) {
        self.hintLab.hidden = NO;
        self.resultLab.hidden = YES;
    }else{
        self.hintLab.hidden = YES;
        self.resultLab.hidden = NO;
        self.resultLab.text = [NSString stringWithFormat:@"识别回答:%@",content];
    }
}

//解压gif的data为图片数组
-(UIImage *)decodeGifImageByData:(NSData *)data {
    //获取data资源器，这个可以直接操作图片data
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nil);
    //获取图片数量 size_t 类似于无符号int
    size_t count = CGImageSourceGetCount(source);
    UIImage * animationImage;
    
    //如果只有一张则直接解压
    if (count <= 1) {
        animationImage = [[UIImage alloc]initWithData:data];
    }
    else {
        NSMutableArray * imageArray = [NSMutableArray arrayWithCapacity:count];
        NSTimeInterval duration = 0.0f;
        //遍历获取每一张图片
        for (size_t i = 0; i < count; i++) {
            //解析图片拿到图片画笔拿到图片画笔
            CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
            duration += [self imageDurationAtIndex:i source:source];
            //scale:图片缩放因子 默认1  orientation:图片绘制方向 默认网上
            [imageArray addObject:[UIImage imageWithCGImage:imageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            CGImageRelease(imageRef);
        }
        
        //如果没有抓取到图片播放时间，则按照0.1秒一张的方式来了播放
        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }
        animationImage = [UIImage animatedImageWithImages:imageArray duration:duration];
    }
    
    
    CFRelease(source);
    return animationImage;
}

//获取每一张图片的持续时间
-(float)imageDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    float imageDuration = 0.1f;
    //获取指定图像的属性信息 如宽、高、持续时间等都在里面 详情参考 CGImageProperties
    CFDictionaryRef cfImageProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    if (!cfImageProperties) {
        return imageDuration;
    }
    NSDictionary * imageProperties = (__bridge NSDictionary *) cfImageProperties;
    //拿到gif图的属性信息 获取每一帧的时间
    NSDictionary * gifProperties = [imageProperties valueForKey:(NSString *)kCGImagePropertyGIFDictionary];
    NSNumber * delayTime = [gifProperties valueForKey:(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTime != nil) {
        return delayTime.floatValue;
    }
    
    return imageDuration;
}

@end
